<template>
    <div class="container">
    <!-- 头部 -->
    <div class="card" style="margin-bottom: 5px;">
        <el-input placeholder="搜索" :prefix-icon="Search"  style="width: 240px; margin-right: 5px;" v-model="data.name"></el-input>
        <el-button type="primary" @click="getMessage">查 询</el-button>
        <el-button type="warning" @click="reset">重 置</el-button>
    </div>
    <!-- 内容区1 -->
    <div class="card" style="display: flex; align-items: center;">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="warning" @click="batch">批量删除</el-button>
        <el-upload
            class="excel-upload"
            action="http://localhost:8080/article/import"
            :show-file-list="false"
            :on-success="importSuccess"
            style="margin: 0 10px 0 10px;"
            >
            <el-button type="primary">导入</el-button>        
        </el-upload>
        
        <el-button type="success" @click="dataExport">导出</el-button>
    </div>
    <!-- 内容区2 -->
    <div class="card" style="margin-top: 5px;">
        <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="标题" prop="title"/>
            <el-table-column label="封面" prop="img">
                <template #default="scope">
                    <el-image :src="'http://localhost:8080/files/download/'+scope.row.img" :preview-src-list=[scope.row.img] preview-teleported
                    alt="" style="width: 50px; height: 50px; border-radius: 50%;" />  
                </template>

            </el-table-column>
            <el-table-column label="描述" prop="description" show-overflow-tooltip/>
            <el-table-column label="内容">
                <template #default="scope">
                    <el-button type="primary" @click="view(scope.row.content)">查看内容</el-button>
                </template>   
            </el-table-column>
            <el-table-column label="时间" prop="time"/>
            <el-table-column label="操作"  width="120">
                <template #default="scope">
                    <el-button type="primary" circle :icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                    <el-button type="danger" circle :icon="DeleteFilled" @click="del(scope.row)"></el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <!-- 分页组件 -->
     <div class="card">
        <el-pagination
        v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="data.total"
        @current-change="getMessage"
        @size-change="getMessage"
        />
     </div>

     <!-- 添加修改对话框 -->
     <el-dialog
        v-model="addView"
        title="文章信息"
        width="500"
    >
        <el-form :model="data.form" style="padding: 20px;">
            <el-form-item label="标题"  prop="title">
                <el-input v-model="data.form.title" autocomplete="off" placeholder="请输入标题"/>
            </el-form-item>
            <el-form-item label="封面"  prop="img">
                <el-upload
                    v-model:file-list="imgList"
                    class="upload-demo"
                    multiple
                    action="http://localhost:8080/files/upload"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    :limit="1"
                    :on-exceed="handleExceed"
                >
                    <el-button type="primary">上传封面</el-button>
                </el-upload>
            </el-form-item>

            <el-form-item label="描述" >
                <el-input v-model="data.form.description" type="textarea" :row="3" autocomplete="off" placeholder="请输入描述。。。"/>
            </el-form-item>
            <el-form-item label="内容">
                <div style="border: 1px solid #ccc; width: 100%;">
                    <Toolbar
                        style="border-bottom: 1px solid #ccc;"
                        :editor="editorRef"
                        :mode="mode" />
                    <Editor
                        style="height: 500px; overflow-y: hidden;"
                        v-model="data.form.content"
                        :mode="mode"
                        :defaultConfig="editorConfig"
                        @onCreated="handleCreated" />
                </div>
            </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
            <el-button @click="addView = false">取消</el-button>
            <el-button type="primary" @click="addMessage">确认</el-button>
        </span>
        </template>
    </el-dialog>

    
     <!-- 查看内容弹窗 -->
     <el-dialog
        v-model="data.viewVisible"
        title="内容"
        width="50%"
        :close-on-click-modal="false"
        destroy-on-close
    >
    <div class="editor-content-view" style="padding: 20px;" v-html="data.content"></div>
    <template #footer>
        <span class="dialog-footer">
            <el-button @click="data.viewVisible=false">关闭</el-button>
        </span>
    </template>
    </el-dialog>
</div>
</template>

<script setup>
    import request from '@/utils/request';
    import { ElMessage,ElMessageBox } from 'element-plus';
    import { ref,reactive,onMounted,shallowRef,onBeforeUnmount } from 'vue';
    import {DeleteFilled,Edit,Search} from '@element-plus/icons-vue'
    import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
    import '@wangeditor/editor/dist/css/style.css';


    const addView = ref(false)
    const delList = ref([])//删除列表
    const data = reactive({
        name:null,
        tableData:[],
        pageSize:10,//分页数量
        pageNum:1,//当前页面
        total:0,//数据总量
        form:{},//要添加的数据
        viewVisible:false,
        content:null
    })
    const imgList = ref([])

    //获取信息
    const getMessage = () =>{
        request.get('/article/selectPage',{
            params:{
                pageSize:data.pageSize,
                pageNum:data.pageNum,
                name:data.name
            }
        }).then(res => {
            console.log(res,"res");
            data.tableData = res.data.list
            data.total = res.data.total
        })
    }

    //wangeditor初始化
    const editorRef = shallowRef();
    const mode = 'default';
    const editorConfig = { MENU_CONF: {} };
    //图片上传配置
    editorConfig.MENU_CONF['uploadImage']={
        server : request.baseUrl + '/files/wang/upload',
        fieldName : 'file'
    }

    onBeforeUnmount(() => {
        const editor = editorRef.value;
        if (editor != null) {
            editor.destroy();
        }
    });

    const handleCreated = (editor) => {
        editorRef.value = editor;
    };

    const view = (content) =>{
        data.content = content
        data.viewVisible = true
    }

    //重置
    const reset = () =>{
        data.name = null
        data.pageNum = 1
        data.pageSize = 10
        getMessage()
    }

    //导入
    const importSuccess = (res) =>{
        console.log(res,"import");
        if(res.code=='200'){
            ElMessage.success("导入成功")
            getMessage()
        }else{
            ElMessage.error(data.msg)
        }
    }

    //导出
    const dataExport = () =>{
        window.open('http://localhost:8080/article/export')
    }

    // 处理文件预览
    const handlePreview = (file) => {
      console.log('预览文件:', file);
      // 这里可以添加文件预览的逻辑，比如打开一个弹窗显示文件内容
      ElMessage.info(`预览文件: ${file.name}`);
    };

    // 处理文件移除
    const handleRemove = (file, fileList) => {
      console.log('移除文件:', file);
      console.log('剩余文件列表:', fileList);
      ElMessage.warning(`文件 ${file.name} 已移除`);
    };

    // 在文件移除前的确认操作
    const beforeRemove = (file) => {
      return ElMessageBox.confirm(`确定移除文件 ${file.name} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        return true; // 返回 true 表示允许移除
      }).catch(() => {
        return false; // 返回 false 表示取消移除
      });
    };

    // 处理文件超出限制
    const handleExceed = (files, fileList) => {
      console.log('超出限制的文件:', files);
      console.log('当前文件列表:', fileList);
      ElMessage.warning('超出文件上传限制，最多只能上传 1 个文件');
    };

    const handleUpdate = (row)=>{
        addView.value = true
        data.form = row
    }

    const handleAdd = () =>{
        addView.value = true
        data.form = {}//初始化数据
    }

    //批量删除
    const handleSelectionChange = (rows) =>{
        delList.value = rows.map(v => {
            const id = Number(v.id)
            return id
        })
    }
    const batch = () =>{
        if(delList.value.length !== 0){
            console.log(delList.value,"delList.value");
            ElMessageBox.confirm('删除数据后无法恢复，确认删除吗','确认删除',{type:'warning'}).then(()=>{
                request.delete("/article/batch",{data:delList.value}).then(res =>{
                    if(res.code == '200'){
                        ElMessage.success("成功")
                        getMessage()
                    }else{
                        ElMessage.error(res.data);
                    }
                }) 
            })
        }else{
            ElMessage.error("请选择要删除的内容")
        }
    }

    //编辑信息
    const edit = () =>{    
        request.put('/article/update', data.form).then(res=>{
            if(res.code == '200'){
                ElMessage.success("修改成功")
                addView.value = false
                getMessage()
            }else{
                ElMessage.error(res.msg)
            }
        }) 
    }

    //删除消息
    const del = (row) =>{
        request.delete(`/article/delete/${row.id}`).then(res =>{
            if(res.code == '200'){
                ElMessage.success('删除成功')
                getMessage()//冲洗加载数据
            }else{
                ElMessage.error(res.msg)
            }
        }) 
    }

    //增加弹窗
    const add = () =>{
        request.post('/article/add',data.form).then(res=>{
        console.log(res,"ressss");
            if(res.code == '200'){
                ElMessage.success('添加成功')
                getMessage()//冲洗加载数据
            }else{
                ElMessage.error(res.msg)
            }

        })
    }


    // 增加信息
    const addMessage = () => {
        // console.log(imgList.value[0].response.data,"imgList");
        if (imgList.value.length > 0 && imgList.value[0].response && imgList.value[0].response.data) {
            data.form.img = imgList.value[0].response.data.split('/').pop(); // 取第一个文件的 URL
        } else {
            data.form.img = ''; // 如果没有上传图片，设置为空
        }
        if(data.form.id != null){
            edit()
        }else{
            add()
        }
    }

    onMounted(()=>{
        getMessage()
    })

</script>